package com.zx.disneyholidays.page;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.zx.disneyholidays.MyApplication;
import com.zx.disneyholidays.R;
import com.zx.disneyholidays.bean.CardBean;
import com.zx.disneyholidays.bean.TicketCardBean;
import com.zx.disneyholidays.net.BaseResponse;
import com.zx.disneyholidays.net.HttpUtils;
import com.zx.disneyholidays.net.ResponseCallBack;
import com.zx.disneyholidays.utils.FileUtils;
import com.zx.disneyholidays.utils.MediaUtils;
import com.zx.disneyholidays.utils.StatusBarUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;
import widgets.KidDialogV2;
import widgets.MenuDialog;

public class CardEditActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    SharedPreferences sharedPreferences = MyApplication.applicationContext.getSharedPreferences("MAIN", Context.MODE_PRIVATE);
    EditText tvPhoneNumber;
    TextView tvSearch;
    ImageView ivCard;
    ImageView ivDelete;

    private MenuDialog mMenuDialog;

    private String TEMP_IMAGE_FILE_NAME = "temp.jpg";
    private final static String CROP_FILE_NAME = "crop_head.jpg";
    public static final String PERMISSION_CAMERA = "PERMISSION_CAMERA";
    public static final String PERMISSION_PHOTO = "PERMISSION_PHOTO";
    public static final int PERMISSION_CAMERA_CODE = 1001;
    public static final int PERMISSION_PHOTO_CODE = 10002;
    public static final int ACTION_FROM_ALBUM = 10002;
    public static final int ACTION_FROM_CAMERA = 10001;
    public static final int ACTION_FROM_CROP = 10003;
    public static final int ACTION_FROM_MODIFY_NAME = 10004;
    public static final int ACTION_FROM_MODIFY_TELE_NUMBER = 10005;
    public static final int ACTION_FROM_MODIFY_REMARK = 10006;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_edit);

        StatusBarUtils.setColor(this, Color.WHITE);
        StatusBarUtils.setTextDark(this, true);

        tvPhoneNumber = findViewById(R.id.et_phone);
        tvSearch = findViewById(R.id.tv_search);
        ivCard = findViewById(R.id.iv_card);
        ivDelete = findViewById(R.id.iv_delete);


        handleEvents();
    }

    private void handleEvents() {
        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestCardInfo(tvPhoneNumber.getText().toString());
            }
        });

        ivCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //showUpdateProfileDialog();
                boolean hasStoragePermission = checkExternalStoragePermission(CardEditActivity.this);
                if (hasStoragePermission) {
                    MediaUtils.getFromPhotos(CardEditActivity.this);// 从相相册获取
                } else {
                    EasyPermissions.requestPermissions(
                            new PermissionRequest.Builder(CardEditActivity.this, PERMISSION_PHOTO_CODE, permissions)
                                    .setRationale("打开相册，需要获取本地存储权限")
                                    .setPositiveButtonText("授权")
                                    .setNegativeButtonText("暂不")
                                    .build());
                }
            }
        });


        findViewById(R.id.fl_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveCardInfo();
            }
        });


        findViewById(R.id.fl_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CardEditActivity.this.finish();
            }
        });


        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CardEditActivity.this.finish();
            }
        });

        findViewById(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivCard.setImageDrawable(null);
                erCodeUrl = "";
            }
        });
    }


    private void requestCardInfo(String phoneNumber) {
        Map<String, String> params = new HashMap<>();
        params.put("phone", phoneNumber);
        HttpUtils.instance.httpGet("api/index/search_user", params, new ResponseCallBack() {
            @Override
            public void onSuccess(BaseResponse data) {
                if (data.getCode() != 1) {
                    Toast.makeText(MyApplication.applicationContext, data.getMsg(), Toast.LENGTH_SHORT).show();
                    return;
                }

                try {
                    CardBean cardBean = JSONObject.parseObject(data.getData(), CardBean.class);
                    bindView(cardBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(int error, String msg) {
                Toast.makeText(MyApplication.applicationContext, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void bindView(CardBean cardBean) {
        if (cardBean == null
                || cardBean.getUser() == null
                || cardBean.getTicket() == null) {
            return;
        }
        ((TextView) findViewById(R.id.tv_name)).setText(cardBean.getUser().getName());
        ((TextView) findViewById(R.id.tv_card_number)).setText(cardBean.getTicket().getCard_no());
        ((TextView) findViewById(R.id.tv_card_name)).setText(cardBean.getTicket().getName());
        ((TextView) findViewById(R.id.tv_start_time)).setText(cardBean.getTicket().getStart_date());
        ((TextView) findViewById(R.id.tv_end_time)).setText(cardBean.getTicket().getEnd_date());
        if (!TextUtils.isEmpty(cardBean.getTicket().getQr_image())) {
            erCodeUrl = cardBean.getTicket().getQr_image();
            Glide.with(this)
                    .load(cardBean.getTicket().getQr_image())
                    .into(ivCard);
        }

    }


    /*private void showUpdateProfileDialog() {
        List<String> mTitles = new ArrayList<>();
        mTitles.add("拍照");
        mTitles.add("从相册选择");
        mMenuDialog = new MenuDialog(this, mTitles);
        mMenuDialog.setHeaderTitle("更换头像");
        mMenuDialog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                boolean hasPermission = ContextCompat.checkSelfPermission(CardEditActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
                boolean hasStoragePermission = checkExternalStoragePermission(CardEditActivity.this);
                switch (position) {
                    case 0:
                        if (hasPermission && hasStoragePermission) {
                            String status = Environment.getExternalStorageState();
                            if (status.equals(Environment.MEDIA_MOUNTED)) {
                                TEMP_IMAGE_FILE_NAME = System.currentTimeMillis() + "temp.png";
                                MediaUtils.getFromCamera(CardEditActivity.this, com.zx.disneyholidays.utils.FileUtils.createTempFile(TEMP_IMAGE_FILE_NAME));// 从相机获取
                            } else {
                                // 没有SD卡;
                                Toast.makeText(CardEditActivity.this, "手机没有SD卡", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            EasyPermissions.requestPermissions(
                                    new PermissionRequest.Builder(CardEditActivity.this, PERMISSION_CAMERA_CODE, Manifest.permission.CAMERA)
                                            .setRationale("拍照需要相机权限")
                                            .setPositiveButtonText("授权")
                                            .setNegativeButtonText("暂不")
                                            .build());
                        }
                        break;

                    case 1:
                        if (hasStoragePermission) {
                            MediaUtils.getFromPhotos(CardEditActivity.this);// 从相相册获取
                        } else {
                            EasyPermissions.requestPermissions(
                                    new PermissionRequest.Builder(CardEditActivity.this, PERMISSION_PHOTO_CODE, permissions)
                                            .setRationale("打开相册，需要获取本地存储权限")
                                            .setPositiveButtonText("授权")
                                            .setNegativeButtonText("暂不")
                                            .build());
                        }
                        break;
                    default:
                        break;
                }
                mMenuDialog.dismiss();
            }
        });
        mMenuDialog.show();
    }
*/
    private String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    public boolean checkExternalStoragePermission(Context context) {
        boolean isAllPermissionGranted = true;
        for (int i = 0; i < permissions.length; i++) {
            isAllPermissionGranted = isAllPermissionGranted &&
                    (ContextCompat.checkSelfPermission(MyApplication.applicationContext, permissions[i]) == PackageManager.PERMISSION_GRANTED);
        }
        return isAllPermissionGranted;
    }

    private KidDialogV2 requestDialog = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ACTION_FROM_CAMERA:
                if (resultCode == RESULT_OK) {
                    uploadErCode(FileUtils.getUriFromFile(CardEditActivity.this, FileUtils.getTempFile(TEMP_IMAGE_FILE_NAME)).getPath());
                    //MediaUtils.getFromCrop(this, , FileUtils.createTempFile(CROP_FILE_NAME));
                }
                break;

            case ACTION_FROM_ALBUM:
                if (resultCode == RESULT_OK) {
                    if (data != null && data.getData() != null) {
                        uploadErCode(getPath(CardEditActivity.this, data.getData()));
                        //MediaUtils.getFromCrop(this, data.getData(), FileUtils.createTempFile(CROP_FILE_NAME));
                    }
                }
                break;

           /* case ACTION_FROM_CROP:
                if (resultCode == RESULT_OK) {
                    mIPresenter.updateUserProfile((FileUtils.getTempFile(CROP_FILE_NAME).getAbsolutePath()));
                } else {
                    KidToast.showMsg(this, "取消上传", Toast.LENGTH_SHORT);
                }
                break;
            case ACTION_FROM_MODIFY_NAME:
                if (resultCode == RESULT_OK) {
                    String name = data.getStringExtra(KEY_NEW_EMP_NAME);
                    updateEMpName(name);
                    mIPresenter.getAccount().getUserInfo().nickname = name;
                }
                break;
            case ACTION_FROM_MODIFY_REMARK:
                if (resultCode == RESULT_OK) {
                    String name = data.getStringExtra(KEY_NEW_EMP_NAME);
                    updateRemark(name);
                    mIPresenter.getAccount().getUserInfo().remark = name;
                }
                break;*/
            default:
                break;
        }

    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
    }

    @AfterPermissionGranted(PERMISSION_CAMERA_CODE)
    private void openCamera() {
        // 在此处执行打开相机的逻辑
        TEMP_IMAGE_FILE_NAME = System.currentTimeMillis() + "temp.png";
        MediaUtils.getFromCamera(CardEditActivity.this, FileUtils.createTempFile(TEMP_IMAGE_FILE_NAME));// 从相机获取
    }

    @AfterPermissionGranted(PERMISSION_PHOTO_CODE)
    private void openPhoto() {
        // 在此处执行打开相机的逻辑
        MediaUtils.getFromPhotos(CardEditActivity.this);// 从相相册获取
    }


    public void onRequestPermissionsResult(
            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        //将结果转发到EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    String erCodeUrl;

    private void uploadErCode(String filePath) {
        HttpUtils.instance.httpPostWithMulti("api/index/upload", filePath, new ResponseCallBack() {
            @Override
            public void onSuccess(BaseResponse data) {
                if (data.getCode() != 1) {
                    Toast.makeText(MyApplication.applicationContext, data.getMsg(), Toast.LENGTH_SHORT).show();
                    return;
                }

                try {
                    JSONObject object = JSONObject.parseObject(data.getData());
                    erCodeUrl = object.getString("fullurl");
                    Glide.with(CardEditActivity.this)
                            .load(erCodeUrl)
                            .into(ivCard);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(int error, String msg) {
                Toast.makeText(MyApplication.applicationContext, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String getPath(Context context, Uri uri) {
        String path = null;
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor == null) {
            return null;
        }
        if (cursor.moveToFirst()) {
            try {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        cursor.close();
        return path;
    }


    private void saveCardInfo() {
        String phoneNumber = tvPhoneNumber.getText().toString();
        if (TextUtils.isEmpty(phoneNumber) || phoneNumber.length() != 11) {
            Toast.makeText(this, "请确认手机号是否有误", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(erCodeUrl) || erCodeUrl.length() == 0) {
            Toast.makeText(this, "请先上传二维码", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("phone", phoneNumber);
        params.put("src", erCodeUrl);
        HttpUtils.instance.httpPost("api/index/set_ticket_qr", JSONObject.toJSONString(params), new ResponseCallBack() {
            @Override
            public void onSuccess(BaseResponse data) {
                if (data.getCode() != 1) {
                    Toast.makeText(MyApplication.applicationContext, data.getMsg(), Toast.LENGTH_SHORT).show();
                    return;
                }

                try {
                    Toast.makeText(MyApplication.applicationContext, data.getMsg(), Toast.LENGTH_SHORT).show();
                    CardEditActivity.this.finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(int error, String msg) {
                Toast.makeText(MyApplication.applicationContext, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }


    // 字体大小不跟随系统
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(getConfigurationContext(newBase));
    }

    private static Context getConfigurationContext(Context context) {
        Configuration configuration = context.getResources().getConfiguration();
        configuration.fontScale = 1;
        return context.createConfigurationContext(configuration);
    }

    /*@Override
    public Resources getResources() {
        Resources res=super.getResources();
        Configuration config=new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config,res.getDisplayMetrics());
        return res;
    }*/

}